package cn.ch.train.business.service;

import cn.ch.train.business.domain.DailyTrain;
import cn.ch.train.business.domain.DailyTrainExample;
import cn.ch.train.business.mapper.DailyTrainMapper;
import cn.ch.train.business.request.DailyTrainQueryParam;
import cn.ch.train.business.request.DailyTrainSaveParam;
import cn.ch.train.business.response.DailyTrainQueryResult;
import cn.ch.train.common.response.PageResult;
import cn.ch.train.common.util.SnowUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class DailyTrainService {
    private static final Logger logger = LoggerFactory.getLogger(DailyTrainService.class);
    @Resource
    private DailyTrainMapper dailyTrainMapper;

    public void save(DailyTrainSaveParam param) {
        DateTime now = DateTime.now();
        DailyTrain dailyTrain = BeanUtil.copyProperties(param, DailyTrain.class);
        if (Objects.isNull(dailyTrain.getId())) {
            dailyTrain.setId(SnowUtil.getSnowFlakeNextId());
            dailyTrain.setCreateTime(now);
            dailyTrain.setUpdateTime(now);
            dailyTrainMapper.insert(dailyTrain);
        } else {
            dailyTrain.setUpdateTime(now);
            dailyTrainMapper.updateByPrimaryKey(dailyTrain);
        }
    }

    public PageResult<DailyTrainQueryResult> queryList(DailyTrainQueryParam param) {
        DailyTrainExample dailyTrainExample = new DailyTrainExample();
        dailyTrainExample.setOrderByClause("date asc, code asc");
        DailyTrainExample.Criteria criteria = dailyTrainExample.createCriteria();
        if (ObjectUtil.isNotNull(param.getDate())) {
            criteria.andDateEqualTo(param.getDate());
        }
        if (ObjectUtil.isNotEmpty(param.getCode())) {
            criteria.andCodeEqualTo(param.getCode());
        }
        PageHelper.startPage(param.getPageNo(), param.getPageSize());
        List<DailyTrain> dailyTrainList = dailyTrainMapper.selectByExample(dailyTrainExample);

        PageInfo<DailyTrain> dailyTrainPageInfo = new PageInfo<>(dailyTrainList);
        logger.info("总行数：{}", dailyTrainPageInfo.getTotal());
        logger.info("总页数：{}", dailyTrainPageInfo.getPages());
        List<DailyTrainQueryResult> dailyTrainQueryList = BeanUtil.copyToList(dailyTrainList, DailyTrainQueryResult.class);
        PageResult<DailyTrainQueryResult> pageResult = new PageResult<>();
        pageResult.setTotal(dailyTrainPageInfo.getTotal());
        pageResult.setList(dailyTrainQueryList);
        return pageResult;
    }

    public void delete(Long id) {
        dailyTrainMapper.deleteByPrimaryKey(id);
    }
}
